﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
using System.Web;
using Microsoft.Win32;

namespace SqueezeboxBridge
{
    public partial class Form1 : Form
    {

        protected const string _regKey = "Software\\Grondwerk.it\\LastFmUriHandler";

        protected Slim _slim;
        protected string[] _players;
        protected Timer _timer = new Timer();
        protected StreamServer _streamServer;

        public Form1(string[] pars)
        {
            InitializeComponent();

            // refresh players
            RefreshPlayers();

            // timer 
            _timer.Tick += new EventHandler(_timer_Tick);

            // URI parameter?
            if (pars.Length > 0)
            {
                LastFmUri.Text = pars[0];
                PlayUri();
            }
        }

        void _timer_Tick(object sender, EventArgs e)
        {
            if (AutoClose.Checked)
                Application.Exit();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            PlayUri();
        }

        private void PlayUri()
        {
            if (_players == null)
                return;

            _slim = new Slim(SqueezeCenterUrl.Text);

            string title = RetrieveUriTitle(LastFmUri.Text);
            string uri = LastFmUri.Text.Replace("lastfm://", "lfm://");
            
            // httpserver
            //_streamServer = new StreamServer(new IPEndPoint(IPAddress.Any, 9091));
            //_streamServer.Start();

            // cache file
            Global.CreateTables();
            StreamCacheFile file = StreamCache.Current.CacheFile(@"D:\Music\The White Stripes\2006 - Elephant\01 - The White Stripes - Seven Nation Army.mp3");
            string newuri = "http://trajano-7:9091/get/" + file.Id;

            // _slim.PlayUri(_players[PlayersCombo.SelectedIndex], uri + " " + title);
            _slim.PlayUri(_players[PlayersCombo.SelectedIndex], newuri + " " + title);

            if (AutoClose.Checked)
            {
                _timer.Interval = 3000;
                _timer.Start();
            }

        }

        private string RetrieveUriTitle(string uri)
        {
            // the uri is DOUBLE UrlEncoded 
            uri = HttpUtility.UrlDecode(HttpUtility.UrlDecode(uri));

            if (uri.StartsWith("lastfm://artist/") && uri.EndsWith("/similarartists"))
            {
                // similar artists radio
                uri = uri.Substring(16, uri.Length - 31) + " Radio";
            }
            else if (uri.StartsWith("lastfm://globaltags/"))
            {
                // global tags radio
                uri = ApplyPascalCasing(uri.Substring(20)) + " Tag Radio";
            }
            else if (uri.StartsWith("lastfm://tag/"))
            {
                // multiple tags radio
                uri = ApplyPascalCasing(uri.Substring(13)).Replace("*", ", ") + " Multiple Tag Radio";
            }
            else
            {
                // TO DO: multiple artists radio, playlists
            }
            // UrlEncode again...once is enough
            return HttpUtility.UrlPathEncode(uri);
        }

        private string ApplyPascalCasing(string str)
        {
            string[] words = str.Split(' ');
            for (int i = 0; i < words.Length; i++)
            {
                words[i] = char.ToUpper(words[i][0]) + words[i].Substring(1);
            }
            return String.Join(" ", words);
        }

        private void Refresh_Click(object sender, EventArgs e)
        {
            StoreSettings();
            RefreshPlayers();
        }

        private void RefreshPlayers()
        {
            try
            {
                // get squeezecenter
                string squeezeCenter = RetrieveSqueezeCenter;

                SqueezeCenterUrl.Text = squeezeCenter;
                _slim = new Slim(squeezeCenter);
                _players = _slim.RetrievePlayers();

                PlayersCombo.Items.Clear();
                for (int i = 0; i < _players.Length; i++)
                {
                    PlayersCombo.Items.Add(_slim.RetrievePlayerName(i));
                }
                                
                if (RetrievePlayerIndex < _players.Length)
                    PlayersCombo.SelectedIndex = RetrievePlayerIndex;
                else
                    PlayersCombo.SelectedIndex = 0;
            }
            catch (SocketException se)
            {
                WrongSettings();
            }
        }

        private void StoreSettings()
        {
            RegistryKey key = Registry.CurrentUser.CreateSubKey(_regKey);
            key.SetValue("SqueezeCenter", SqueezeCenterUrl.Text);
            key.SetValue("PlayerIndex", PlayersCombo.SelectedIndex);
        }

        private string RetrieveSqueezeCenter
        {
            get
            {
                RegistryKey key = Registry.CurrentUser.CreateSubKey(_regKey);
                return (string)key.GetValue("SqueezeCenter", "Enter your SqueezeServer name here");
            }
        }

        private int RetrievePlayerIndex
        {
            get
            {
                RegistryKey key = Registry.CurrentUser.CreateSubKey(_regKey);
                int index = (int)key.GetValue("PlayerIndex", 0);
                if (index < 0)
                    index = 0;
                return index;
            }
        }
        
        private void WrongSettings()
        {
            MessageBox.Show("Please check the SqueezeBox Server name. Just use the bare name or network address, i.e. 'MusicServer' or '192.168.0.10'. Good luck!",
                "SqueezeBox Server unreachable", MessageBoxButtons.OK);
        }

        private void PlayersCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            StoreSettings();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            About about = new About();
            about.ShowDialog(this);
        }
    }
}
